<template>
  <div class="account-manage">
    <div class="account-title">
      <span>{{$t('accountManage.title')}}</span>
      <div style="float: right">
        <el-button @click="openAddAccount">{{$t('accountManage.newAccount')}}</el-button>
      </div>
    </div>
    <el-container>
      <el-aside width="300px">
        <el-input class="search-goods" :placeholder="$t('accountManage.searchAccount')" v-model="searchAccount">
          <template slot="append"><span>{{$t('common.search')}}</span></template>
        </el-input>
        <div class="account-wrapper" v-loading="accountListLoading">
          <div class="account-item" :class="activeAccount.uid == item.uid?'account-item-active':''"
               v-for="(item, index) in accountList" :key="index" @click="handleAccount(item, index)">
            {{item.nick_name}} - {{item.username}}
          </div>
        </div>
      </el-aside>
      <el-main>
        <div v-show="activeAccount.uid">
          <div class="account-op">
            <el-button type="primary" @click="openModifyPassword">{{$t('accountManage.changePassword')}}</el-button>
            <el-button type="danger" @click="deleteAccount(activeAccount)">{{$t('accountManage.deleteAccount')}}</el-button>
          </div>
          <div class="permission-wrapper">
            <div class="permission">
              <div class="permission-title">{{$t('accountManage.permission')}}</div>
              <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">{{$t('accountManage.selectAll')}}
              </el-checkbox>
              <div style="margin: 15px 0;"></div>
              <el-checkbox-group v-model="activeAccount.permission_group"
                                 @change="handleCheckedPermissionChange">
                <el-checkbox v-for="(item, index) in permissionList"
                             :key="index" :label="item.id">{{item.permission}}
                </el-checkbox>
              </el-checkbox-group>
            </div>
          </div>
          <el-button @click="modifyPermissiom(activeAccount, 1)">{{$t('accountManage.submitPermission')}}
          </el-button>
        </div>
      </el-main>
    </el-container>
    <el-dialog width="25%" :title="dialogFormTitle"
               :visible.sync="dialogFormVisible"
               @close="closeDialog"
               center>
      <el-form :model="accountForm" label-position="top" ref="accountForm" label-width="100px">
        <!--帐号-->
        <el-form-item :label="$t('accountManage.account')"
                      prop="account"
                      :rules="[ {required: true, message: $t('accountManage.emptyAccount'), trigger: 'blur'} ]">
          <el-input :placeholder="$t('accountManage.account')" :disabled="dialogFormTitle == $t('accountManage.changePassword')" v-model="accountForm.account"></el-input>
        </el-form-item>
        <!--名称-->
        <el-form-item :label="$t('accountManage.name')"
                      prop="accountName"
                      :rules="[ {required: true, message: $t('accountManage.emptyName'), trigger: 'blur'} ]">
          <el-input :placeholder="$t('accountManage.name')" :disabled="dialogFormTitle == $t('accountManage.changePassword')"  v-model="accountForm.accountName"></el-input>
        </el-form-item>
        <!--密码-->
        <el-form-item :label="$t('accountManage.password')"
                      prop="password"
                      :rules="[ {required: true, message: $t('accountManage.emptyPassword'), trigger: 'blur'} ]">
          <el-input type="password" :placeholder="$t('accountManage.emptyPassword')" v-model="accountForm.password"></el-input>
        </el-form-item>
        <!--确认密码-->
        <!--<el-form-item v-if="dialogFormTitle == $t('accountManage.changePassword')" :label="$t('accountManage.confirmPassword')"-->
                      <!--prop="checkPassword"-->
                      <!--:rules="[ {required: true, message: $t('accountManage.againPassword'), trigger: 'blur'} ]">-->
          <!--<el-input type="password" :placeholder="$t('accountManage.againPassword')" v-model="accountForm.checkPassword"-->
                    <!--@keyup.enter.native="modifyPassword('accountForm',accountForm)" auto-complete="off"></el-input>-->
        <!--</el-form-item>-->
      </el-form>
      <div v-if="dialogFormTitle == $t('accountManage.newAccount')">
        <div style="text-align: center">
          <span class="line"></span>
          <span class="txt">{{$t('accountManage.permissionSetting')}}</span>
          <span class="line"></span>
        </div>
        <div class="permissions">
          <el-checkbox :indeterminate="isIndeterminateDialog" v-model="checkAllDialog"
                       @change="handleCheckAllChangeDialog">{{$t('accountManage.selectAll')}}
          </el-checkbox>
          <div style="margin: 15px 0;"></div>
          <el-checkbox-group v-model="accountForm.permissionGroup"
                             @change="handleCheckedPermissionChangeDialog">
            <el-checkbox v-for="(item, index) in permissionList"
                         :key="index" :label="item.id">{{item.permission}}
            </el-checkbox>
          </el-checkbox-group>
        </div>
      </div>
      <!--提交按钮-->
      <div class="dialog-btn">
        <el-button type="primary" @click="judgeDialog">{{dialogFormTitle}}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  export default {
    name: 'AccountManage',

    data() {
      return {
        newAccount: '', // 新增账号
        searchAccount: '', // 搜索账户
        accountList: [], // 账户列表
        accountListLoading: false, // 账户列表加载
        permissionList: [], // 权限列表
        permissionIds: [], // 权限列表id数组
        checkAll: false, // 多选状态
        checkAllDialog: false,
        isIndeterminate: true, // 多选中间状态 -
        isIndeterminateDialog: false,
        activeAccount: {}, // 被选中的跑堂账号
        dialogFormVisible: false, // dialog显示
        dialogFormTitle: '', // dialog标题
        // 账号表单
        accountForm: {
          account: '',
          accountName: '',
          password: '',
          checkPassword: '',
          permissionGroup: []
        },
        // 账号表单验证
        rules: {
          account: [
            {required: true, message: '帐号不能为空', trigger: 'blur'}
          ],
          accountName: [
            {required: true, message: '名称不能为空', trigger: 'blur'}
          ],
          password: [
            { required: true, message: '请输入密码', trigger: 'blur' }
          ],
          checkPassword: [
            { required: true, message: '请再次输入密码', trigger: 'blur' }
          ]
        }
      }
    },

    props: {},

    components: {},

    created() {
      // 获取权限列表
      this.getPermissionList()
      // 获取跑堂列表
      this.getAccountList()
    },

    watch: {},

    computed: {},

    filters: {},

    methods: {
      // 关闭弹窗
      closeDialog() {
        this.$refs['accountForm'].resetFields()
        // this.accountForm.permissionGroup = []
        this.isIndeterminateDialog = false
      },

      // 获取跑堂列表
      getAccountList() {
        this.accountListLoading = true
        this.$axios.get(`${this.$REQ_URL}app&action=member_list&shopid=${sessionStorage.getItem('shopId')}`).then(res => {
          if (res.data.state === 1) {
            this.accountList = res.data.data
          }
          this.accountListLoading = false
        }).catch(() => {
          this.accountListLoading = false
          this.$message({
            type: 'error',
            message: this.$t('accountManage.failedWaiterList')
          })
        })
      },

      // 获取权限列表
      getPermissionList() {
        this.$axios.get(`${this.$REQ_URL}app&action=GetPermission&shopid=${sessionStorage.getItem('shopId')}`).then(res => {
          if (res.data.state === 1) {
            this.permissionList = res.data.data
            this.permissionList.map(permission => {
              permission.id = `${permission.id}`
              this.permissionIds.push(permission.id)
            })
          }
        }).catch(() => {
          this.$message({
            type: 'error',
            message: this.$t('accountManage.failedPermissionList')
          })
        })
      },

      // 操作账号
      handleAccount(item) {
        this.activeAccount = {...item}
        this.activeAccount.permission_group = this.activeAccount.permission_group.length === 0 ? [] : this.activeAccount.permission_group.split(',')
        if (this.activeAccount.permission_group.length === 0) {
          this.activeAccount.permission_group = []
          this.isIndeterminate = false
          this.checkAll = false
        } else if (this.activeAccount.permission_group.length === this.permissionIds.length) {
          this.isIndeterminate = false
          this.checkAll = true
        } else {
          this.checkAll = false
          this.isIndeterminate = true
        }
      },

      // 操作勾选全选
      handleCheckAllChange(val) {
        this.activeAccount.permission_group = val ? this.permissionIds : []
        this.isIndeterminate = false
      },

      // 操作勾选全选
      handleCheckAllChangeDialog(val) {
        this.accountForm.permissionGroup = val ? this.permissionIds : []
        this.isIndeterminateDialog = false
      },

      // 操作多选
      handleCheckedPermissionChange(value) {
        let checkedCount = value.length
        this.checkAll = checkedCount === this.permissionIds.length
        this.isIndeterminate = checkedCount > 0 && checkedCount < this.permissionIds.length
      },

      // 操作多选
      handleCheckedPermissionChangeDialog(value) {
        let checkedCount = value.length
        this.checkAllDialog = checkedCount === this.permissionIds.length
        this.isIndeterminateDialog = checkedCount > 0 && checkedCount < this.permissionIds.length
      },

      // 修改跑堂权限
      modifyPermissiom(account, code) {
        let param = `&uid=${account.uid}`
        param += code === 1 ? `&permission=${account.permission_group}` : ''
        this.$axios.get(`${this.$REQ_URL}app&action=ChangePwd${param}`).then(res => {
          if (res.data.state === 1) {
            this.$message({
              type: 'success',
              message: this.$t('accountManage.successModify')
            })
            this.getAccountList()
          }
        }).catch(() => {
          this.$message({
            type: 'error',
            message: this.$t('accountManage.failedModify')
          })
        })
      },

      // 判断修改密码还是添加账号
      judgeDialog() {
        this.dialogFormTitle === this.$t('accountManage.changePassword') ? this.modifyPassword('accountForm', this.accountForm, this.activeAccount.uid) : this.addAccount('accountForm', this.accountForm)
      },

      // 修改跑堂密码
      modifyPassword(formName, account, uid) {
        this.$refs[formName].validate((valid) => {
          if (!valid) return
          this.$axios.post(`${this.$REQ_URL}app&action=ChangePwd&uid=${uid}&pwd=${account.password}`).then(res => {
            if (res.data.state === 1) {
              this.$message({
                type: 'success',
                message: this.$t('accountManage.successModify')
              })
              this.dialogFormVisible = false
            } else if (res.data.state === -1) {
              this.$message({
                type: 'error',
                message: res.data.msg
              })
            }
          }).catch(() => {
            this.$message({
              type: 'error',
              message: this.$t('accountManage.failedModify')
            })
          })
        })
      },

      // 添加跑堂账号
      addAccount(formName, account) {
        this.$refs[formName].validate((valid) => {
          if (!valid) return
          this.$axios.post(`${this.$REQ_URL}app&action=add_member&uname=${account.account}&nick_name=${account.accountName}&pwd=${account.password}&permission=${account.permissionGroup}&shopid=${sessionStorage.getItem('shopId')}`).then(res => {
            if (res.data.state === 1) {
              this.$message({
                type: 'success',
                message: this.$t('common.successAdd')
              })
              this.dialogFormVisible = false
              this.getAccountList()
              this.accountForm = {
                permissionGroup: []
              }
              this.$refs.accountForm.resetFields()
              this.isIndeterminateDialog = false
              this.checkAllDialog = false
            } else if (res.data.state === -1) {
              this.$message({
                type: 'error',
                message: res.data.msg
              })
            }
          }).catch(() => {
            this.$message({
              type: 'error',
              message: '网络超时，新增失败'
            })
          })
        })
      },

      // 删除跑堂账号
      deleteAccount(account) {
        this.$confirm(`${this.$t('accountManage.deleteAccountOperation')}:${account.nick_name} - ${account.username}`, this.$t('common.prompt'), {
          confirmButtonText: this.$t('common.confirm'),
          cancelButtonText: this.$t('common.cancel')
        }).then(() => {
          this.$axios.get(`${this.$REQ_URL}app&action=DelMember&uid=${account.uid}`
          ).then(res => {
            if (res.data.state === 1) {
              this.$message({
                type: 'success',
                message: this.$t('common.successDelete')
              })
              this.activeAccount = {}
              this.getAccountList()
            } else {
              this.$message({
                type: 'info',
                message: this.$t('common.failedDelete')
              })
            }
          }).catch(() => {
            this.$message({
              type: 'error',
              message: this.$t('common.failedDelete')
            })
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: this.$t('common.cancelDelete')
          })
        })
      },
      // 打开修改密码
      openModifyPassword() {
        this.dialogFormVisible = true
        this.dialogFormTitle = this.$t('accountManage.changePassword')
        this.accountForm.account = this.activeAccount.username
        this.accountForm.accountName = this.activeAccount.nick_name
      },
      // 打开新增账户
      openAddAccount() {
        this.dialogFormVisible = true
        this.dialogFormTitle = this.$t('accountManage.newAccount')
        this.accountForm = {
          permissionGroup: []
        }
      }
    }
  }
</script>

<style scoped>
  .el-aside {
    overflow: hidden;
    box-sizing: border-box;
    -moz-box-sizing: border-box; /* Firefox */
    -webkit-box-sizing: border-box; /* Safari */
    color: #333;
    padding: 40px;
  }

  .el-main {
    color: #333;
    padding: 40px;
  }

  .el-container {
    margin-top: 40px;
    background-color: #ffffff;
    margin-bottom: 80px;
  }

  .account-manage {
    background: #ffffff;
    box-shadow: 0 3px 10px 0 rgba(0, 0, 0, 0.10);
    padding: 0 40px;
    margin-bottom: 80px;
  }

  .account-title {
    background: #ffffff;
    height: 80px;
    line-height: 80px;
    border-bottom: 1px solid #dedede;
  }

  .account-title span {
    text-align: left;
    font-family: PingFang-SC-Semibold;
    font-size: 20px;
    font-weight: bold;
    color: #000000;
    letter-spacing: 0;
  }

  .account-title >>> .el-button {
    background-color: #ff8214;
    border-bottom: 1px solid #ff8214;
    color: #ffffff;
  }

  .account-wrapper {
    margin-top: 12px;
    border: 1px solid #dedede;
  }

  .account-item {
    height: 40px;
    line-height: 40px;
    padding-left: 24px;
    border-bottom: 1px solid #f0f0f0;
    font-family: PingFang-SC-Regular;
    font-size: 14px;
    color: #000000;
    letter-spacing: 0;
    text-align: left;
    cursor: pointer;
  }

  .account-item-active {
    background: #ff8214;
    color: #ffffff;
    border-bottom: 1px solid #ff8214;
  }

  .account-op {
    padding-bottom: 23px;
    border-bottom: 1px solid #dedede;
  }

  .permission-wrapper {
    padding-top: 28px;
  }

  .permission {
    margin-bottom: 40px;
  }

  .permission-title {
    margin-bottom: 12px;
    font-family: PingFang-SC-Semibold;
    font-size: 16px;
    font-weight: bold;
    color: #000000;
    letter-spacing: 0;
    text-align: left;
  }

  /*按钮*/
  .dialog-btn {
    margin-top: 32px;
    text-align: center;
  }

  .dialog-btn button {
    border: none;
    background:#ff8214;
    border-radius:5px;
    max-width:430px;
    height:40px;
  }

  .line {
    display: inline-block;
    width: 100px;
    border-top: 1px solid #ccc ;
  }

  .txt {
    font-family:PingFang-SC-Semibold;
    font-size:16px;
    /*font-weight: bold;*/
    color:#000000;
    vertical-align: middle;
    padding: 0 10px;
  }

  .permissions {
    text-align: left;
    margin-top: 23px;
  }

  .permissions >>> .el-checkbox__label {
    width: 40px;
  }

  .permissions >>> .el-checkbox__label {
    width: 40px;
  }

  .permissions >>> .el-checkbox:nth-child(1) {
    margin-left: 30px;
  }
</style>
